/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

basePath="/rssmaster/"; 
 
FeedWindow = function() {
    this.feedUrl = new Ext.form.ComboBox({
        id: 'feed-url',
        fieldLabel: 'Введите адрес источника (RSS/Atom)',
        emptyText: 'http://example.com/blog/feed',
        width: 450,
        validationEvent: false,
        validateOnBlur: false,
        msgTarget: 'under',
        triggerAction: 'all',
        displayField: 'url',
        mode: 'local',

        listeners:{
            valid: this.syncShadow,
            invalid: this.syncShadow,
            scope: this
        },
        tpl: new Ext.XTemplate(
                '<tpl for="."><div class="x-combo-list-item">',
                '<em>{url}</em><strong>{text}</strong>',
                '<div class="x-clear"></div>',
                '</div></tpl>'),
        store: new Ext.data.SimpleStore({
            fields: ['url', 'text'],
            data : this.defaultFeeds
        })
    });

    this.form = new Ext.FormPanel({
        labelAlign:'top',
        items:this.feedUrl,
        border: false,
        bodyStyle:'background:transparent;padding:10px;'
    });

    FeedWindow.superclass.constructor.call(this, {
        title: 'Добавить источник',
        iconCls: 'feed-icon',
        id: 'add-feed-win',
        autoHeight: true,
        width: 500,
        resizable: false,
        plain:true,
        modal: true,
        y: 100,
        autoScroll: true,
        closeAction: 'hide',

        buttons:[{
            text: 'Добавить',
            handler: this.onAdd,
            scope: this
        },{
            text: 'Отмена',
            handler: this.hide.createDelegate(this, [])
        }],

        items: this.form
    });

    this.addEvents({add:true});
}

FeedRenameWindow = function() {
    this.feedText = new Ext.form.TextField({
        id: 'feed-rename-url',
        fieldLabel: 'Переименовать',
        emptyText: '',
        width: 450,
        validationEvent: false,
        validateOnBlur: false,
        msgTarget: 'under',
        triggerAction: 'all',
        displayField: 'url',
        mode: 'local',

        listeners:{
            valid: this.syncShadow,
            invalid: this.syncShadow,
            scope: this
        },
        tpl: new Ext.XTemplate(
                '<tpl for="."><div class="x-combo-list-item">',
                '<em>{url}</em><strong>{text}</strong>',
                '<div class="x-clear"></div>',
                '</div></tpl>')
    });
	
	 this.feedUrl = new Ext.form.Hidden({
		  value: '',
		  id: 'feed-rename-url_hidden'
	}); 

    this.form = new Ext.FormPanel({
        labelAlign:'top',
        items:(this.feedText),
        border: false,
        bodyStyle:'background:transparent;padding:10px;'
    });

    FeedRenameWindow.superclass.constructor.call(this, {
        title: 'Переименовать источник',
        iconCls: 'feed-icon',
        id: 'rename-feed-win',
        autoHeight: true,
        width: 500,
        resizable: false,
        plain:true,
        modal: true,
        y: 100,
        autoScroll: true,
        closeAction: 'hide',

        buttons:[{
            text: 'Сохранить',
            handler: this.onRename,
            scope: this
        },{
            text: 'Отмена',
            handler: this.hide.createDelegate(this, [])
        }],

        items: this.form
    });

    this.addEvents({add:true});
}

Ext.extend(FeedWindow, Ext.Window, {
    defaultFeeds : [
        ['http://www.xakep.ru/articles/rss/default.asp?rss_cat=news', 'Хакер - Новости'],
        ['http://www.xakep.ru/articles/rss/default.asp?rss_cat=post',  'Хакер - Статьи'],
        ['http://www.forexua.com/ru/analytic/ta.xml', 'Форекс Украина'],
        ['http://work.com.ua/rss/jobs/?category=1', 'Работа ИТ']
    ],

    show : function(){
        if(this.rendered){
            this.feedUrl.setValue('');
        }
        FeedWindow.superclass.show.apply(this, arguments);
    },

    onAdd: function() {
        this.el.mask('Проверка...', 'x-mask-loading');
        var url = this.feedUrl.getValue();
        Ext.Ajax.request({
            url: 'feed-proxy.php',
            params: {feed: url},
            success: this.validateFeed,
            failure: this.markInvalid,
            scope: this,
            feedUrl: url
        });
    },

    markInvalid : function(){
        this.feedUrl.markInvalid('Выбранный вами источник некорректный.');
        this.el.unmask();
    },

    validateFeed : function(response, options){
        var dq = Ext.DomQuery;
        var url = options.feedUrl;
        try{
			var json = Ext.util.JSON.decode(response.responseText);
			if (typeof(json.rss.channel)!="undefined") {
				var text = json.rss.channel.title;
				var description = json.rss.channel.description;
				
				this.el.unmask();
				this.hide();
				
				return this.fireEvent('validfeed', {
                    url: url,
                    text: text,
                    description: description
                });
			}
        }catch(e){
        }
        this.markInvalid();
    }
});

Ext.extend(FeedRenameWindow, Ext.Window, {

    show : function(){
        FeedRenameWindow.superclass.show.apply(this, arguments);
    },

    onRename: function() {
		var url = this.feedUrl.getValue();
		var text = this.feedText.getValue();
		if (url && text) {
			var items = Ext.util.JSON.decode(cp.get("feeditems","{}"));
			items[url] = text;
			cp.set("feeditems",Ext.util.JSON.encode(items));
		}
		this.hide();
		return this.fireEvent('renamefeed', {
			url: url,
			text: text
		});
    },
	
	setValues: function() {
		if (arguments[0].text && arguments[0].url) {
			this.feedText.setValue(arguments[0].text);
			this.feedUrl.setValue(arguments[0].url);
		}
	}
	
});